package com.xjcs.saplingplan.view

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import com.xjcs.saplingplan.R
import com.xjcs.saplingplan.model.bean.Bubble
import kotlin.math.pow
import kotlin.random.Random

class BubbleView : View {
    private var bubbles: MutableList<Bubble>? = null
    private var paint: Paint? = null
    private var animator: ValueAnimator? = null
    private var random: Random? = null

    // 自定义属性
    private var bubbleCount = 1 // 默认气泡数量
    private var minRadius = 30f // 最小半径
    private var maxRadius = 80f // 最大半径
    private var maxSpeed = 5f // 最大速度

    constructor(context: Context?) : super(context) {
        init(null)
    }

    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
        init(attrs)
    }

    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        init(attrs)
    }

    private fun init(attrs: AttributeSet?) {
        bubbles = ArrayList()
        paint = Paint(Paint.ANTI_ALIAS_FLAG)

        // 解析自定义属性
        if (attrs != null) {
            val ta = context.obtainStyledAttributes(attrs, R.styleable.BubbleView)
            bubbleCount = ta.getInt(R.styleable.BubbleView_bubbleCount, bubbleCount)
            minRadius = ta.getDimension(R.styleable.BubbleView_minRadius, minRadius)
            maxRadius = ta.getDimension(R.styleable.BubbleView_maxRadius, maxRadius)
            maxSpeed = ta.getDimension(R.styleable.BubbleView_maxSpeed, maxSpeed)
            ta.recycle()
        }
        random =  Random.Default

        // 初始化气泡
//        generateBubbles()
    }

    private fun generateBubbles() {
        bubbles?.clear()
        for (i in 0 until bubbleCount) {
            var overlap: Boolean
            var x: Float
            var y: Float
            var radius: Float

            do {
                overlap = false
                // 随机生成气泡的半径和位置
                radius = minRadius + random!!.nextFloat() * (maxRadius - minRadius)
                x = radius + random!!.nextFloat() * (width - 2 * radius)
                y = radius + random!!.nextFloat() * (height - 2 * radius)

                // 检查新气泡是否与已有气泡重叠
                for (bubble in bubbles!!) {
                    val distance = Math.sqrt(
                        (x - bubble.x).toDouble().pow(2.0) + (y - bubble.y).toDouble().pow(2.0)
                    ).toFloat()
                    if (distance < radius + bubble.radius) {
                        overlap = true // 重叠了，需要重新生成
                        break
                    }
                }
            } while (overlap) // 如果重叠，重新生成气泡的位置

            // 生成气泡的速度和颜色
            val dx = (random!!.nextFloat() - 0.5f) * 2 * maxSpeed
            val dy = (random!!.nextFloat() - 0.5f) * 2 * maxSpeed
            val color =
                Color.argb(255, random!!.nextInt(256), random!!.nextInt(256), random!!.nextInt(256))

            // 将新气泡添加到列表
            bubbles?.add(Bubble(x, y, radius, dx, dy, color))
        }
    }

    // 启动动画
    private fun startAnimation() {
        if (animator != null && animator!!.isRunning) {
            animator!!.cancel()
        }
        animator = ValueAnimator.ofFloat(0f, 1f)
        animator?.repeatCount = ValueAnimator.INFINITE
        animator?.setDuration(16) // 大约 60 FPS
        animator?.addUpdateListener {
            updateBubbles()
            invalidate()
        }
        animator?.start()
    }

    // 更新气泡位置并检测碰撞
    private fun updateBubbles() {
        for (i in bubbles!!.indices) {
            val bubble = bubbles!![i]
            bubble.update(width, height)

            // 检测与其他气泡的碰撞
            for (j in i + 1 until bubbles!!.size) {
                val other = bubbles!![j]
                if (bubble.isColliding(other)) {
                    bubble.handleCollision(other)
                }
            }
        }
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        for (bubble in bubbles!!) {
            paint!!.color = bubble.color
            canvas.drawCircle(bubble.x, bubble.y, bubble.radius, paint!!)
        }
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        generateBubbles()
        startAnimation()
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        if (animator != null) {
            animator!!.cancel()
        }
    }
}